<?php
class XPHP_Widget_Attribute_DataTable extends XPHP_Action_Attribute_Abstract
{
    /**
     * Các columns
     * @var array
     */
    private $_columns;
    /**
     * Gán tham số truyền vào cho Attribute
     */
    public function init ($properties)
    {
        if (count($properties) > 0) {
            $this->_columns = $properties;
        } else {
            throw new XPHP_Attribute_Exception(
            'XPHP_Widget_Attribute_DataTable bắt buộc tham số truyền vào mảng các cột');
        }
    }
    /**
     * Sự kiện này được thực thi khi trước khi action được thực thi
     */
    public function onActionExecute ()
    {
        $model = $this->_controller->getModel();
        /** @var XPHP_Db_ActiveRecord $db*/
        $db = $model->getActiveRecord();
        /* 
       	 * Phân trang
       	 */
        if ($this->_controller->hasParams('iDisplayStart') &&
         $this->_controller->getParams('iDisplayLength') != '-1') {
            $db->limit($this->_controller->getParams('iDisplayLength'), 
            $this->_controller->getParams('iDisplayStart'));
        }
        /*
    	 * Ordering
    	 */
        if ($this->_controller->hasParams('iSortCol_0')) {
            $colSortIndex = (int) $this->_controller->getParams('iSortingCols') -
             1;
            $colSort = $this->_columns[$colSortIndex];
            $sortDirect = $this->_controller->getParams('sSortDir_0');
            $db->order_by($colSort, $sortDirect);
        }
        /*
         *  Filter
         */
        if ($this->_controller->hasParams('sSearch') &&
         $this->_controller->getParams('sSearch') != "") {
            for ($i = 0; $i < count($this->_columns); $i ++) {
                $db->or_like($this->_columns[$i], 
                mysql_real_escape_string(
                $this->_controller->getParams('sSearch')));
            }
        }
        //aaData
        $result = $db->get()->result();
        //sEcho
        $sEcho = intval($this->_controller->getParams('sEcho'));
        //iTotalRecords
        $iTotalRecords = intval($db->count_all_results());
        //iTotalDisplayRecords
        $iTotalDisplayRecords = count($result);
        $this->_controller->dataTable = array("aaData" => $result, 
        "sEcho" => $sEcho, "iTotalRecords" => $iTotalRecords, 
        "iTotalDisplayRecords" => $iTotalDisplayRecords);
    }
}